package com.marry.consumer.listener;

import com.alibaba.fastjson.JSONObject;
import com.marry.consumer.entity.MailMessageModel;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSender;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author ml
 * @create 2017-08-03--15:55
 */
@Component("mailMessageListenerAdapter")
public class MailMessageListenerAdapter extends MessageListenerAdapter {

    @Autowired
    private JavaMailSender javaMailSender;


    @Value("${mail.username}")
    private String mailUserName;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {

        String messageBody=new String(message.getBody());

        MailMessageModel mailMessageModel= JSONObject.toJavaObject(JSONObject.parseObject(messageBody),MailMessageModel.class);

        String to=mailMessageModel.getTo();

        String subject=mailMessageModel.getSubject();

        String text=mailMessageModel.getText();
        sendHtmlMail(to,subject,text);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

    }

    private void sendHtmlMail(String to, String subject, String text) throws MessagingException {
        MimeMessage mimeMessage= javaMailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper=new MimeMessageHelper(mimeMessage);

        mimeMessageHelper.setFrom(mailUserName);

        mimeMessageHelper.setTo(to);

        mimeMessageHelper.setSubject(subject);

        mimeMessageHelper.setText(text);


        javaMailSender.send(mimeMessage);


    }
}
